#coding=utf-8

'''
Author: Create by hanjt

Date: 2018-12-28

Description: The script is to post many email.

Version of Python: 3.7 (The earliest version of Python must be 3.0. )
'''

import logging
from email import encoders
from email.header import Header
from email.mime.text import MIMEText
from email.utils import parseaddr, formataddr
import smtplib
import re

LOG_FORMAT = "%(asctime)s - %(levelname)s - %(message)s"
DATE_FORMAT = "%m/%d/%Y %H:%M:%S %p"
logging.basicConfig(level=logging.DEBUG, format=LOG_FORMAT)
# logging.basicConfig(filename='mkcm.log', level=logging.DEBUG, format=LOG_FORMAT)


'''
群发邮件
'''
class PostEmail:

    def __init__(self):
        pass

    '''
    验证一个邮箱的格式
    '''
    def _validate_email(self, email):
        if len(email) > 7:
            if re.match("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$", email) != None:
                return True
        return False

    
    '''
    格式化一个邮件地址
    '''
    def _format_addr(self, s):
        name, addr = parseaddr(s)
        return formataddr((Header(name, 'utf-8').encode(), addr))

    '''
    发送邮件
    '''
    def post_email(self, from_email, pwd, to_emails, smtp_server):
        msg = MIMEText('hello, send by Python...', 'plain', 'utf-8')
        msg['From'] = self._format_addr('韩锦涛 <%s>' % from_email)
        # msg['To'] = self._format_addr('App操作指南 <%s>' % to_emails)
        msg['Subject'] = Header('测试群发邮件脚本', 'utf-8').encode()
        # SMTP协议默认端口是25
        server = smtplib.SMTP(smtp_server, 25)
        server.set_debuglevel(1)
        server.login(from_email, pwd)
        server.sendmail(from_email, to_emails, msg.as_string())
        server.quit()
    
    '''
    读取待发送的邮件列表
    '''
    def read_emails(self, fp):
        with open(fp, 'r') as f:
            readlines = f.readlines()
            for line in readlines:
                if self._validate_email(line.strip()) is not True:
                    readlines.remove(line)
            return readlines

    '''
    程序主控制器
    '''
    def main(self):
        from_email = input("登录邮箱地址：")
        pwd = input("登录邮箱密码：")
        smtp_server = input("SMTP服务地址,形如：smtp.163.com：")
        fp = input("待发送邮件列表txt文件地址：")
        # fp = 'emails.txt'
        emails = self.read_emails(fp)
        self.post_email(from_email, pwd, emails, smtp_server)

postEmail = PostEmail()
postEmail.main()